package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //判断是否套餐,
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            //如果是套餐，需要把审核状态设置初始化
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            //如果不是套餐，需要把审核状态设置无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //设置默认的销售状态(下架)和创建时间
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 根据id 查单条
        ServiceItem oldObj = this.get(serviceItem.getId());

        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())){
            //如果是上架状态，不允许修改的,抛出异常
            throw new BusinessException("该项目已上架,不可修改");
        }

        // 如果是下架状态,是套餐,且在审核中, 不能编辑,并抛出异常
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus()))
        {
            throw new BusinessException("套餐项目审核中,不能进行修改");
        }
        // 如果是下架状态，套餐，处于审核通过,如果此时修改，应该把状态修改成初始化
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus()))
        {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            // 其他情况，原来是什么状态，应该设置什么状态.
            serviceItem.setAuditStatus(oldObj.getAuditStatus());
        }
        // 如果是套餐, 将审核状态改为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            // 如果不是套餐, 将审核状态该为无需审核状态
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        // 防止前台恶意对销售状态进行设置，代码中主动设置销售状态为下架状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }


    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    // 上架
    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = get(id);
        // 1.如果已上架就不需要再进行上架
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw new BusinessException("该项目已上架,不可重复上架");
        }
        // 2.如果是套餐,且不是审核通过的状态，是不能上架的，抛出异常.
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())
                && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()))
        {
            throw new BusinessException("该套餐项目需要审核通过后才可以上架!");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    // 下架
    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    // 套餐审核
    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        // 合理性校验
        // 根据id获取服务单项对象
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage()) // 不是套餐
                || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) // 审核中
                || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) // 审核通过
                || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus()) // 无需审核
                || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus()) // 上架状态
        ){
            throw new BusinessException("非法操作, 请更换套餐");
        }

        // new 套餐审核
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(id);
        audit.setServiceItemInfo(serviceItem.getInfo()); // 设置服务项目备注信息
        audit.setServiceItemPrice(serviceItem.getDiscountPrice()); // 折扣价
        audit.setServiceItemName(serviceItem.getName());
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName()); // 创建当前登录用户
        audit.setBpmninfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(director); // 设置审核人
        carPackageAuditService.save(audit);


        Map<String, Object> params = new HashMap<>();
        if (director != null) {
            params.put("director", director);
        }
        if (finance != null) {
            params.put("finance", finance);
        }
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());

        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey
                ( bpmnInfo.getActProcessKey(), String.valueOf(audit.getId()), params);

        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.update(audit);
        // 修改服务单项状态为审核中
        serviceItemMapper.updateAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer statusInit) {
        serviceItemMapper.updateAuditStatus(serviceItemId, statusInit);
    }
}
